package com.grad.why.studentsystem.Interceptor;

import com.grad.why.studentsystem.domain.User;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


public class BackLoginInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求的url
		String url = request.getRequestURL().toString();
		// 获取项目根路径
		String contextPath = request.getContextPath();
		if (StringUtils.hasText(contextPath)) {
			String[] urls = url.split(contextPath);
			if (urls.length == 2){
				url = urls[1]; // 获取出去根路径及以前的字符串
			}
		}
		// 允许登录页和登录验证的访问
		String[] allowPages = new String[]{"login","checkCode","checkLogin","signOut","evaluate","Test"};
		for(String s : allowPages){
			if(url.endsWith(s)){
				return true;
			}
		}
		HttpSession session = request.getSession();
		// 获取登录后存入session中的adminRole对象
		User adminRole = (User) session.getAttribute("user");
		if (adminRole == null){
			// 没有进行登录的访问
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print("<script type='text/javascript' charset='UTF-8'>"
						+ "alert('禁止未登录者访问'); "
						+ "window.location.href='" + contextPath + "/studentManageSystem/login';"
					+ "</script>");
			out.flush();
			out.close();
			return false;
		}
		
		return true;
	}
}
